import type { Context } from 'koa'
import {
  inseretCarpoolMember,
  updateCarpoolMember,
  deleteCarpoolMember,
  selectCarpoolMember,
  selectAllCarpoolMember,
} from '../service/carpoolmember.service.ts'
import {
  CarpoolMemberCreateError,
  CarpoolMemberUpdateError,
  CarpoolMemberDeleteError,
  CarpoolMemberSelectError,
} from '../constant/err.type.ts'
import { CarpoolMemberInfo } from '../interface/params.interface.ts'
import moment from 'moment'
import { sendMail } from '../config/nodemailer.ts'

let count: number = 0

class CarpoolMemberController {
  // 查询拼车成员
  async getCarpoolMember(ctx: Context) {
    try {
      const carpoolMemberIds = ctx.request.query.carpoolMemberIds as string
      const ids = carpoolMemberIds.split(',')
      const data = await selectCarpoolMember(ids)
      ctx.echo({ data })
    } catch (error) {
      CarpoolMemberSelectError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolMemberSelectError, ctx)
    }
  }

  // 新增拼车成员
  async addCarpoolMember(ctx: Context) {
    try {
      const {
        memberName,
        startDate,
        endDate,
        email,
        expire,
        remark,
        carpoolType,
      } = ctx.request.body
      await inseretCarpoolMember({
        memberName,
        startDate,
        endDate,
        email,
        expire,
        remark,
        carpoolType,
      })
      ctx.echo({ msg: '新增成功' })
    } catch (error) {
      CarpoolMemberCreateError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolMemberCreateError, ctx)
    }
  }

  // 更新拼车成员
  async editCarpoolMember(ctx: Context) {
    try {
      const {
        carpoolMemberId,
        memberName,
        startDate,
        endDate,
        email,
        expire,
        remark,
        carpoolType,
      } = ctx.request.body
      await updateCarpoolMember({
        carpoolMemberId,
        memberName,
        startDate,
        endDate,
        email,
        expire,
        remark,
        carpoolType,
      })
      ctx.echo({ msg: '更新成功' })
    } catch (error) {
      CarpoolMemberUpdateError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolMemberUpdateError, ctx)
    }
  }

  // 删除拼车成员
  async removeCarpoolMember(ctx: Context) {
    try {
      const { carpoolMemberId } = ctx.params
      await deleteCarpoolMember({ carpoolMemberId })
      ctx.echo({ msg: '删除成功' })
    } catch (error) {
      CarpoolMemberDeleteError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolMemberDeleteError, ctx)
    }
  }

  private async checkVipExpired() {
    try {
      const data: CarpoolMemberInfo[] = await selectAllCarpoolMember()
      for (let user of data) {
        if (moment(user.endDate).isBefore(moment())) {
          const options = {
            subject: '【会员拼车】',
            html: '',
          }
          options.html = `<p>
            <span style='color: red'>${user.remark}</span>
            的
            <span style='color: red'>${user.memberName}</span>
            的
            <span style='color: red'>${user.carpoolTypeInfo.carpoolTypeName}</span> 已经到期了！
          </p>`
          if (user.expire === '1') {
            // 更新为已过期状态
            await updateCarpoolMember({
              carpoolMemberId: user.carpoolMemberId,
              expire: '0',
            })
            await sendMail(options)
          }
        } else if (user.expire === '0') {
          // 未过期时，保证状态为未过期
          // 更新为未过期状态
          await updateCarpoolMember({
            carpoolMemberId: user.carpoolMemberId,
            expire: '1',
          })
        }
      }
      if (data.every(user => moment(user.endDate).isAfter(moment()))) {
        console.log(
          `[ ${moment().format(
            'YYYY-MM-DD HH:mm:ss SSS',
          )} ] 没有人拼车时间过期！`,
        )
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 启动自动查询拼车是否过期
  startAutoTask() {
    console.log(`查询拼车是否过期任务执行中……`)
    // 一天检查一次
    setInterval(
      async () => {
        count++
        console.log(
          `[ ${moment().format(
            'YYYY-MM-DD HH:mm:ss SSS',
          )} ] 会员拼车：第 ${count} 次检查`,
        )
        await this.checkVipExpired()
      },
      1000 * 60 * 60 * 24,
    )
  }
}

const carpoolMemberController = new CarpoolMemberController()
carpoolMemberController.startAutoTask()
export const {
  getCarpoolMember,
  addCarpoolMember,
  editCarpoolMember,
  removeCarpoolMember,
} = carpoolMemberController
export default carpoolMemberController
